import React from 'react'
import FilterTitle from '../FilterTitle'
import FilterPicker from '../FilterPicker'
import FilterMore from '../FilterMore'
import styles from './index.module.scss'
import { getHousesConditionApi } from '@/api/house'
// 导入 Spring 组件
import { Spring } from 'react-spring/renderprops'

// 标题高亮状态
// true 表示高亮； false 表示不高亮

export default class Filter extends React.Component {
  state = {
    titleSelectedStatus: {
      area: false,
      mode: false,
      price: false,
      more: false
    },
    // 控制FilterPicker或者FilterMore组件的展示或隐藏
    openType: '',
    // 所有筛选条件数据
    filtersData: {},
    // 筛选条件的选中值
    selectedValues: {
      area: ['area', 'null'],
      mode: ['null'],
      price: ['null'],
      more: []
    }
  }

  componentDidMount () {
    this.body = document.body
    this.getFiltersData()
  }

  // 获取所有筛选条件的方法
  async getFiltersData () {
    // 获取当前定位城市id
    const { value } = JSON.parse(localStorage.getItem('hkzf_city'))
    const { data: res } = await getHousesConditionApi({ id: value })
    // console.log('获取的数据', res)
    this.setState({
      filtersData: res.body
    })
  }

  // 对其他标题的状态判断，这里判断的一句就是这个selectedVal是不是还是原来的默认值
  // 如果是，那他的状态还是false，如果不是，那就证明修改过，那他就是true
  judgeHightLight (key, selectedVal) {
    let valueStatus = false
    if (
      key === 'area' &&
      (selectedVal.length !== 2 || selectedVal[0] !== 'area')
    ) {
      // 高亮
      valueStatus = true
    } else if (key === 'mode' && selectedVal[0] !== 'null') {
      // 高亮
      valueStatus = true
    } else if (key === 'price' && selectedVal[0] !== 'null') {
      // 高亮
      valueStatus = true
    } else if (key === 'more' && selectedVal.length !== 0) {
      // 选中filtermore组件
      valueStatus = true
    } else {
      valueStatus = false
    }
    return valueStatus
  }

  // FilterTitle传递过来的点击事件
  // 修改组件的高亮状态
  onTitleClick = type => {
    // 点击之后就会有弹窗，就给body设置一个样式
    this.body.classList.add('body-fixed')
    // 标题选中状态对象和筛选条件的选中值对象
    const { titleSelectedStatus, selectedValues } = this.state
    // 创建新的标题选中状态对象
    const newTitleSelectedStatus = { ...titleSelectedStatus }
    Object.keys(newTitleSelectedStatus).forEach(key => {
      if (key === type) {
        newTitleSelectedStatus[type] = true
        return
      }
      // 对其他标题的状态判断，这里判断的一句就是这个selectedVal是不是还是原来的默认值
      // 如果是，那他的状态还是false，如果不是，那就证明修改过，那他就是true
      newTitleSelectedStatus[key] = this.judgeHightLight(
        key,
        selectedValues[key]
      )
    })
    this.setState({
      // 展示对话框
      openType: type,
      // 使用新的标题选中状态对象来更新
      titleSelectedStatus: newTitleSelectedStatus
    })
  }

  // 取消或隐藏遮罩层
  onCancel = () => {
    let type = this.state.openType
    // 点击之后就会有弹窗，就给body设置一个样式
    // console.log('点击了取消')
    this.body.classList.remove('body-fixed')
    const { titleSelectedStatus, selectedValues } = this.state
    // 创建新的标题选中状态对象
    const newTitleSelectedStatus = { ...titleSelectedStatus }
    // 菜单高亮逻辑处理
    newTitleSelectedStatus[type] = this.judgeHightLight(
      type,
      selectedValues[type]
    )
    this.setState(() => {
      return {
        openType: '',
        // 更新菜单高亮状态数据
        titleSelectedStatus: newTitleSelectedStatus
      }
    })
  }

  // 点确定按钮取消或隐藏遮罩层
  onSave = (type, value) => {
    // console.log(type, value)
    const { titleSelectedStatus } = this.state
    // 创建新的标题选中状态对象
    const newTitleSelectedStatus = { ...titleSelectedStatus }
    const newSelectedValues = {
      ...this.state.selectedValues,
      [type]: value
    }
    // 菜单高亮逻辑处理
    newTitleSelectedStatus[type] = this.judgeHightLight(type, value)
    this.setState(() => {
      return {
        openType: '',
        // 更新菜单高亮状态数据
        titleSelectedStatus: newTitleSelectedStatus,
        selectedValues: newSelectedValues
      }
    })
    // 筛选条件数据
    const filters = {}
    // 解构筛选数据
    const { area, mode, price, more } = newSelectedValues
    // 取到区域关键字
    const areaKey = area[0]
    // 区域的值
    let areaValue = 'null'
    // 处理区域的取值
    if (area.length === 3) {
      areaValue = area[2] !== 'null' ? area[2] : area[1]
    }
    // 将处理好的区域数据添加到 filter 中
    filters[areaKey] = areaValue
    // console.log('打印的区域名单', area)
    // console.log('打印的价格', price)
    // 方式和租金
    filters.mode = mode[0]
    filters.price = price[0]
    // 更多筛选条件 more
    filters.more = more.join(',')
    // console.log('获取的删选的数据',filters);
    this.props.onFilter(filters)
    // 页面回到顶部
    window.scrollTo(0, 0)
  }

  // 封装renderFilterPicker来渲染FilterPicker组件
  renderFilterPicker () {
    const {
      openType,
      filtersData: { area, subway, rentType, price },
      selectedValues
    } = this.state
    if (openType !== 'area' && openType !== 'mode' && openType !== 'price') {
      return null
    }
    let data = []
    let cols = 3
    let defaultValue = selectedValues[openType]
    switch (openType) {
      case 'area':
        data = [area, subway]
        cols = 3
        // console.log(data)
        break
      case 'mode':
        data = rentType
        cols = 1
        break
      case 'price':
        data = price
        cols = 1
        break
      default:
        break
    }
    return (
      <FilterPicker
        key={openType}
        onCancel={this.onCancel}
        onSave={(type, value) => this.onSave(type, value)}
        data={data}
        cols={cols}
        type={openType}
        defaultValue={defaultValue}
      ></FilterPicker>
    )
  }

  // 封装渲染filtermore的组件
  renderFillterMore () {
    const {
      openType,
      selectedValues,
      filtersData: { roomType, oriented, floor, characteristic }
    } = this.state

    if (openType !== 'more') {
      return null
    }
    const data = {
      roomType,
      oriented,
      floor,
      characteristic
    }
    const defaultValue = selectedValues.more
    return (
      <FilterMore
        defaultValue={defaultValue}
        data={data}
        type={openType}
        onSave={this.onSave}
        onCancel={this.onCancel}
      />
    )
  }

  // 渲染遮罩层div
  renderMask () {
    const { openType } = this.state
    // 遮罩层是否隐藏
    const isHide = !(
      openType === 'area' ||
      openType === 'mode' ||
      openType === 'price'
    )
    return (
      <Spring from={{ opacity: 0 }} to={{ opacity: isHide ? 0 : 1 }}>
        {props => {
          // 说明遮罩层已经完成动画效果，隐藏了
          if (props.opacity === 0) {
            return null
          }
          return (
            <div
              style={props}
              className={styles.mask}
              onClick={this.onCancel}
            />
          )
        }}
      </Spring>
    )
  }

  render () {
    const { titleSelectedStatus } = this.state
    return (
      <div className={styles.root}>
        {/* 前三个菜单对应的遮罩层 */}
        {this.renderMask()}
        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle
            titleSelectedStatus={titleSelectedStatus}
            onClick={this.onTitleClick}
          ></FilterTitle>
          {/* 前三个菜单对应的内容 */}
          {this.renderFilterPicker()}
          {/* 最后一个菜单对应的内容： */}
          {this.renderFillterMore()}
        </div>
      </div>
    )
  }
}
